# 这是一种基于类的router定义方式 
require 'sinatra/base'

require 'sinatra/flash'
require_relative './lib/wordguesser_game.rb'

class WordGuesserApp < Sinatra::Base

  enable :sessions
  register Sinatra::Flash
  
  before do
    @game = session[:game] || WordGuesserGame.new('')
  end
  
  after do
    session[:game] = @game
  end
  
  # These two routes are good examples of Sinatra syntax
  # to help you with the rest of the assignment
  # 下面是Sinatra语法的好示例，帮助你理解接下来的任务
  get '/' do
    redirect '/new'
  end
  
  get '/new' do
    # "hello world"
    erb :new
  end
  
  post '/create' do
    # 注释：获取参数中的word或者调用wordGuesserGame中的get_random_word方法获取一个随机的单词
    # NOTE: don't change next line - it's needed by autograder!
    # 注意：不要修改下一行，autograder需要它
    word = params[:word] || WordGuesserGame.get_random_word

    # 注释：调用WordGuesserGame中的new方法，将前面的word传进去，得到@game，然后重定向到/show
    @game = WordGuesserGame.new(word)
    redirect '/show'
  end
  
  # Use existing methods in WordGuesserGame to process a guess.
  # If a guess is repeated, set flash[:message] to "You have already used that letter."
  # If a guess is invalid, set flash[:message] to "Invalid guess."
  # 使用WordGuesserGame中存在的方法，来处理一个猜测请求
  # 如果这个猜测是重复的，设置刷新信息提示“你已经用过这个单词了”
  # 如果这个猜测是非法的，设置刷新信息提示“非法请求”
  post '/guess' do
    letter = params[:guess].to_s[0]
    ### YOUR CODE HERE ###
    begin
      valid = @game.guess(letter)
    rescue ArgumentError
      flash[:message] = "Invalid guess."
    else
      unless valid
        flash[:message] = "You have already used that letter."
      end
    end
    
    redirect '/show'
  end
  
  # Everytime a guess is made, we should eventually end up at this route.
  # Use existing methods in WordGuesserGame to check if player has
  # won, lost, or neither, and take the appropriate action.
  # Notice that the show.erb template expects to use the instance variables
  # wrong_guesses and word_with_guesses from @game.
  # 每一个产生的猜测请求，我们最终都应该在这个路径中结束
  # 使用WordGuesserGame中存在的方法，检查这个玩家是成功了、失败了、还是都不是，采取恰当的反应动作
  # 注意 show.erb模板应当适用实例变量，wrong_guesser和word_with_guesses从@game中
  get '/show' do
    ### YOUR CODE HERE ###
    erb :show # You may change/remove this line
  end
  
  get '/win' do
    ### YOUR CODE HERE ###
    erb :win # You may change/remove this line
  end
  
  get '/lose' do
    ### YOUR CODE HERE ###
    erb :lose # You may change/remove this line
  end
  
end
